<template>
    <div class="container">
        <div
            style="width: 100%;height: 6%;display: flex;flex-direction: row;background-color: white;align-items: center;padding-left:20px;">
            <i class="el-icon-back" style="color: #7d5e01;font-size:25px;font-weight:bold;" @click="backToTop"></i>
            <span style="font-size: 20px;font-weight: bold;">&nbsp;&nbsp;面试场景选择</span>
            <div style="margin-left:auto;margin-right:10px">
                <label for="customCount"><strong>自定义问答轮次：</strong></label>
                <el-input-number id="customCount" v-model="customInterviewCount" :min="3" :max="20" :step="1"
                    style="margin-left: 0px; width: 50px;" :controls="false" placeholder="请输入次数(>=3)" />
            </div>
            <div class="button-area">
                <button class="next-button" @click="jumpToNext()">下一步 ></button>
            </div>
        </div>

        <div style="width: 96%;height: 20%;display: flex;flex-direction: row;justify-content: space-between;border-radius: 10px;background-color: white;box-shadow: 0 4px 20px rgba(0, 0, 0, 0.02);padding: 15px;    margin-left: 2%;
    margin-right: 2%;">
            <div style="width: 60%;height: 100%;display: flex;flex-direction: column;">
                <div class="env-content-top" ref="envContent">
                    <p><strong>目标岗位</strong></p><br>
                    <div style="display: flex;flex-direction: row;column-gap: 15px;">
                        <div class="env-position">
                            <p>技术领域</p>
                            <el-select v-model="form.tcode" clearable filterable placeholder="请选择技术领域"
                                class="product-input" @change="techSelect" allow-create>
                                <el-option v-for="(item, index) in arr_technology_categories" :key="index"
                                    :label="item.label" :value="item.value" />
                            </el-select>
                        </div>
                        <div class="env-position">
                            <p>意向职位</p>
                            <el-select v-model="form.pcode" clearable filterable placeholder="请选择意向职位"
                                class="product-input" @change="positionSelect" allow-create>
                                <el-option v-for="(item, index) in filteredRoles" :key="index" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </div>
                        <div class="env-position">
                            <p>擅长语言</p>
                            <el-select v-model="form.lcode" multiple clearable filterable placeholder="请选择擅长语言"
                                class="product-input" @change="languageSelect">
                                <el-option v-for="(item, index) in arr_language" :key="index" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </div>
                    </div>
                    <p v-if="jobRequirement">职位概述：</p>
                    <div class="requirement-box" v-if="jobRequirement">
                        <div>{{ jobRequirement }}</div>
                    </div>
                </div>
            </div>
            <div
                style="width: 40%;height: 100%;display: flex;flex-direction: column;justify-content: center;padding-left:20px;padding-top:20px">
                <SelectableCheckboxGroup ref="sceneSelect" label="面试场景" :options="[
                    { label: '技术面试', value: 'technical' },
                    { label: '压力面试', value: 'pressure' },
                    { label: '项目经验面试', value: 'project' },
                    { label: '案例面试', value: 'case' },
                    { label: '行为面试', value: 'behavioral' },
                    { label: '薪资谈判', value: 'salary' }
                ]" v-model="form.sceneFields" @update="handleSceneUpdate" />
            </div>
        </div>
        <div
            style="width: 96%;height: 73%;margin-left:2%;margin-right:2%;display: flex;flex-direction: row;justify-content: space-between;border-radius: 10px;background-color: white;box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);padding: 20px;">
            <!-- 左侧内容区域 -->
            <div style="height: 100%;width:60%;">
                <div class="env-content-top">
                    <p><strong>面试官</strong></p>
                    <div class="ai-interviewer-box">
                        <div class="ai-interviewer" v-for="(interviewer, index) in interviewers" :key="index"
                            :class="{ selected: selectedInterviewer === interviewer.name }"
                            @click="selectInterviewer(interviewer.name)">
                            <img :src="interviewer.avatar" alt="面试官照片" class="interviewer-img" />
                            <div class="interviewer-sub">
                                <p style="line-height: 30px;"><strong>{{ interviewer.name }}</strong></p>
                                <p style="font-size:14px;line-height: 25px;">
                                    &nbsp;&nbsp;&nbsp;&nbsp;{{ interviewer.identity }}
                                </p>
                                <!-- <p style="font-size: 12px;line-height: 16px;">推荐面试场景：</p> -->
                                <div class="interviewer-scenes">
                                    <div class="scene-item" v-for="(scene, sIndex) in interviewer.sceneList"
                                        :key="sIndex"
                                        :class="{ suitable: scene.suitable, unsuitable: !scene.suitable }">
                                        {{ scene.name }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <p style="height: 36px;padding-top: 10px;"><strong>上传简历</strong></p>
                    <el-radio-group v-model="resumeChoice">
                        <!-- <el-radio v-for="(resume, index) in predefinedResumes" :key="index" :label="resume.value">
                            {{ resume.label }}
                        </el-radio> -->
                        <el-radio label="custom">上传简历文件</el-radio>
                    </el-radio-group>

                    <!-- 自定义上传器 -->
                    <div v-if="resumeChoice === 'custom'" style="margin-top: 10px;">
                        <input type="file" @change="handleFileChange" accept=".doc,.docx,.pdf" />
                        <el-button size="small" type="primary" @click="uploadResume"
                            :disabled="!selectedFile">解析简历</el-button>
                        <div class="el-upload__tip">仅支持 PDF 或 DOC/DOCX 格式文件</div>
                    </div>

                    <!-- 状态信息 -->
                    <div v-if="loading">解析中，请稍候...</div>
                    <div v-if="error" style="color:red">{{ error }}</div>
                    <!-- <div v-if="result"> -->
                    <!-- <p>解析结果：</p>
                        <pre class="pre-line">{{ formattedResult }}</pre>
                    </div> -->

                </div>
            </div>

            <!-- 右侧区域 -->
            <div class="ai-image">
                <div style="display: flex; flex-direction: column; gap: 10px;width: 100%;height: 25%;">
                    <span style="font-weight: bold;">面试模式</span>
                    <span style="line-height:1.5;">&nbsp;&nbsp;我们提供“练习”和“模拟”两种模式，您可以根据自身需求选择合适的方式进行面试准备。</span>

                </div>
                <img src="@/assets/images/scene/mode-bg-img.png" alt="装饰图片" class="mode-bg-img" />

                <div style="display: flex; flex-direction: row; gap: 10px;width: 100%;height: 75%;">
                    <button class="pattern-practice" :class="{ active: selectedMode === 'practice' }"
                        @click="selectMode('practice')">
                        <span class="scene-title">练习模式</span>
                        <span class="scene-sub-title">【对于面试问题提供参考回答】</span>
                        <span class="scene-sub-title">对于每个回答提供智能分析（优劣-矫正）</span>
                        <img src="@/assets/images/scene/practice-bg-img.png" alt="装饰图片" class="practice-bg-img" />
                    </button>
                    <button class="pattern-real" :class="{ active: selectedMode === 'real' }"
                        @click="selectMode('real')">
                        <span class="scene-title">模拟模式</span>
                        <span class="scene-sub-title">【还原真实面试场景】</span>
                        <span class="scene-sub-title">自主作答，考验临场反应与表达能力</span>
                        <img src="@/assets/images/scene/real-bg-img.png" alt="装饰图片" class="practice-bg-img" />
                    </button>

                </div>
            </div>

        </div>


    </div>

</template>

<script>
import request from '@/utils/request';
import { mapActions } from 'vuex';
import axios from 'axios';
import jobRequirements from '@/assets/position/jobRequirements';
import roleOptions from '@/assets/position/role-options';
import SelectableCheckboxGroup from './InterviewSceneSelect.vue';
import { interviewers } from '@/assets/interview/interviewers.js'; // 假设面试官数据存储在这个 JSON 文件中

export default {
    // components: { JNPFForm, ExportBox },
    components: {
        SelectableCheckboxGroup
    },
    data() {
        return {
            form: {
                pcode: '',
                tcode: '', // 技术领域选项绑定字段
                lcode: [], // 擅长语言选项绑定字段
                sceneFields: []
            },
            // 技术领域
            arr_technology_categories: [
                { label: '计算机软件', value: 'software' }, // 计算机软件
                { label: '智能系统', value: 'intelligent_systems' }, // 智能系统
                { label: '机器人', value: 'robotics' }, // 机器人
                { label: '云计算', value: 'cloud_computing' }, // 云计算
                { label: '物联网', value: 'iot' }, // 物联网
                { label: '大数据', value: 'big_data' }, // 大数据
                { label: '人工智能', value: 'ai' } // 人工智能
            ],
            // 擅长语言
            arr_language: [
                { label: 'C/C++', value: 'cpp' },
                { label: 'Java', value: 'java' },
                { label: 'Python', value: 'python' },
                { label: 'JavaScript/TypeScript', value: 'js_ts' },
                { label: 'Go', value: 'go' },
                { label: 'Rust', value: 'rust' },
                { label: 'Kotlin', value: 'kotlin' },
                { label: 'Swift', value: 'swift' },
                { label: 'Ruby', value: 'ruby' },
                { label: 'PHP', value: 'php' }
            ],
            jobRequirement: '', // 用于存储职位要求
            interviewers: interviewers, // 面试官数据
            selectedInterviewer: null,
            resumeChoice: '', // 当前选中的简历
            predefinedResumes: [
                { label: '默认简历 A', value: 'resumeA' },
                { label: '默认简历 B', value: 'resumeB' }
            ],
            fileList: [], // 上传的文件列表
            selectedFile: null,
            base64FileContent: "",
            result: null,
            error: "",
            loading: false,
            selectedMode: '',
            customInterviewCount: 3,
        }
    },
    computed: {
        filteredRoles() {
            return roleOptions[this.form.tcode] || [];
        },
        formattedResult() {
            return JSON.stringify(this.result, null, 2);
        },
    },
    watch: {
        'form.tcode': function (newVal) {
            console.log('技术领域变化:', newVal);
            // 当技术领域变化时，清空职位和语言
            this.form.pcode = '';
            this.form.lcode = '';
        },
        'form.pcode': function (newVal) {
            console.log('职位变化:', newVal);
            // 当职位变化时，更新职位要求
            this.jobRequirement = jobRequirements[newVal] || '暂无职位要求';
        }
    },
    methods: {
        selectMode(mode) {
            this.selectedMode = mode;
        },
        // 处理场景选择更新
        handleSceneUpdate({ value }) {
            console.log('场景选择更新:', value);
            this.form.sceneFields = value;
        },
        handleUpdate(field, { value }) {
            this.formData[field] = value;
        },
        techSelect(value) {
            this.form.tcode = value;
            this.$store.dispatch('userSelection/updateTechField', value);
            console.log('信息1', value)
        },
        positionSelect(value) {
            this.form.pcode = value;
            this.jobRequirement = jobRequirements[value] || '暂无职位要求';
            this.$store.dispatch('userSelection/updatePosition', value);
            console.log('信息2', value)
            // 平滑滚动到最底部
            this.$nextTick(() => {
                const container = this.$refs.envContent;
                if (container) {
                    container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
                }
            });
        },
        languageSelect(val) {
            this.form.lcode = val;
            this.$store.dispatch('userSelection/updateLanguages', val);
            console.log('信息3', val)
        },

        jumpToNext() {
            if (!this.selectedMode) {
                this.$message.warning('请先选择练习模式或模拟模式');
                return;
            }
            this.$store.dispatch('scene/saveInterviewMode', this.selectedMode);
            console.log('选中的模式:', this.selectedMode);
            if (this.form.sceneFields.length === 0) {
                this.$message.warning('由于您没有选择面试场景，将启用默认面试场景');
            }
            this.$store.dispatch('scene/saveSelectedScenes', this.form.sceneFields);
            const selectedScenes = this.$store.getters['scene/getSelectedScenes'];
            this.$store.dispatch('scene/saveInterviewCount', this.customInterviewCount);
            console.log('面试次数:', this.customInterviewCount);
            //this.$router.push({ path: '/simulate' });
            this.$router.push({ path: '/guide1' });
            // this.$router.push({ path: '/style' });
        },
        backToTop() {
            this.$confirm('是否放弃当前场景选择并返回首页？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    // 用户点击“确定”
                    this.$router.push({ path: '/homePage' });
                    // this.$refs.aiAvatar.closeAll();
                })
                .catch(() => {
                    // 用户点击“取消”，无需处理
                });
        },
        selectInterviewer(name) {
            this.selectedInterviewer = name;
            // 从面试官数据中找到对应的面试官信息
            const interviewer = this.interviewers.find(item => item.name === name);
            if (interviewer) {
                // 保存面试官信息到Vuex
                this.$store.dispatch('scene/saveInterviewer', interviewer);
                console.log('保存面试官到Vuex:', interviewer);
                // 如果已经进入面试页面，通知虚拟人更新（可选，根据路由判断）
                if (this.$route.path === '/simulate') {
                    this.$emit('updateInterviewer', interviewer);
                }
            }
        },
        handleFileChange(event) {
            this.error = "";
            this.result = null;
            const file = event.target.files[0];
            if (!file) {
                this.selectedFile = null;
                this.base64FileContent = "";
                return;
            }

            const allowedTypes = [
                "application/msword",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/pdf",
            ];
            if (!allowedTypes.includes(file.type)) {
                this.error = "请上传.doc、.docx或.pdf格式的简历文件";
                this.selectedFile = null;
                return;
            }

            this.selectedFile = file;

            const reader = new FileReader();
            reader.onload = () => {
                const base64String = reader.result.split(",")[1];
                this.base64FileContent = base64String;
            };
            reader.onerror = () => {
                this.error = "读取文件失败";
                this.selectedFile = null;
            };
            reader.readAsDataURL(file);
        },

        async uploadResume() {
            if (!this.selectedFile || !this.base64FileContent) {
                this.error = "请先选择有效的简历文件";
                return;
            }

            this.error = "";
            this.result = null;
            this.loading = true;

            const url = "https://resumesdk.market.alicloudapi.com/ResumeParser";
            const appcode = "55eda8e822e2421499fcc94005405d82"; // TODO：安全起见，建议使用代理服务器转发

            const data = {
                file_name: this.selectedFile.name,
                file_cont: this.base64FileContent,
                need_avatar: 0,
            };

            try {
                const response = await axios.post(url, data, {
                    headers: {
                        Authorization: "APPCODE " + appcode,
                        "Content-Type": "application/json; charset=UTF-8",
                    },
                });

                if (response.status === 200) {
                    this.result = response.data.result;
                    // 存入 Vuex
                    this.$store.dispatch('resumeSDK/setResumeResult', this.result, null, 2);
                    console.log('简历信息', JSON.stringify(this.result, null, 2));
                } else {
                    this.error = `请求失败，状态码：${response.status}`;
                }
            } catch (err) {
                this.error =
                    err.response && err.response.data
                        ? `请求错误：${JSON.stringify(err.response.data)}`
                        : `请求错误：${err.message}`;
            } finally {
                this.loading = false;
            }
        },

    }
}
</script>

<style scoped>
.container {
    padding-bottom: 2%;
    display: flex;
    flex-direction: column;
    height: 100%;
    gap: 2%;
    /* padding: 0.5%; */
    box-sizing: border-box;
    background-color: rgb(255, 250, 240);
}

/* 左侧数字人头像 */
.ai-image {
    position: relative;
    background-color: #FFF;
    display: flex;
    flex-direction: column;
    row-gap: 10px;
    /* border: 1px solid #3f66c2; */
    border-radius: 10px;
    height: 100%;
    width: 40%;
    padding: 22px;
    padding-bottom: 0px;
}

.ai-image p {
    text-align: left;
    width: 100%;
    margin: 0;
    padding: 20px;
}

.avatar-img {
    max-width: 80%;
    height: auto;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* 右侧内容框 */
.box {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 12px;
    padding: 22px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    height: 100%;
    width: 45%;
    font-size: medium;
    row-gap: 15px;
    background-color: white;
}

.env-content {
    overflow: auto;
    column-gap: 15px;
    font-size: medium;
    color: #333;
    margin-bottom: 16px;
    height: 90%;
}

.env-content-top {
    overflow: auto;
    column-gap: 15px;
    font-size: medium;
    color: #333;
    height: 100%;
    width: 100%;
    border-right: #8f8f8f solid 0.5px;
    padding-right: 15px;
}

.env-position {
    display: flex;
    flex-direction: column;
    column-gap: 15px;
    row-gap: 5px;
    font-size: medium;
    color: #333;
    margin-bottom: 16px;
    white-space: pre-wrap;
    width: 100%;
    height: 15%;
}

.requirement-box {
    background-color: #fff;
    padding: 10px;
    border-radius: 6px;
    border: #d4d3d3 solid 0.5px;
    margin-top: 10px;
    margin-bottom: 10px;
}

/* 面试官列表栏 */
.ai-interviewer-box {
    margin-top: 10px;
    height: 80%;
    display: flex;
    flex-direction: column;
    border-radius: 10px;
    border: #dcdfe6 solid 1px;
    overflow: auto;
}

/* 隐藏滚动条但保留滚动能力 */
.env-content::-webkit-scrollbar,
.ai-interviewer-box::-webkit-scrollbar {
    display: none;
    /* Chrome / Safari / Edge */
}

.env-content,
.ai-interviewer-box {
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE 10+ */
}

/* 面试官名片 */
.ai-interviewer {
    margin-top: 10px;
    margin-left: 2%;
    width: 95%;
    height: 140px;
    border-radius: 10px;
    border: #dcdfe6 solid 1px;
    display: flex;
    gap: 10px;
    flex-direction: row;
    align-items: center;
    background-color: white;
}

.ai-interviewer.selected {
    border: 2px solid #FFA500;
    box-shadow: 0 4px 12px rgba(255, 165, 0, 0.4);
    background-color: #FFF7E6;
}


/* 面试官头像 */
.interviewer-img {
    height: 80%;
    aspect-ratio: 16 / 9;
    margin-left: 2%;
    background-color: #f8f7c1;
}

/* 面试官基本信息块 */
.interviewer-sub {
    height: 80%;
    flex: 1;
    font-size: 14px;
    /* 占据剩余空间（即父宽 - 图像宽 - gap） */
    margin-right: 2%;
    display: flex;
    flex-direction: column;
}

.interviewer-scenes {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    font-size: 12px;
    gap: 3px;
    /* 项目之间的间距 */
}

.scene-item {
    display: flex;
    /* 开启 Flex 布局 */
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    padding: 10px 16px;
    margin: 5px;
    border-radius: 4px;
    font-size: 9px;
    /* color: black; */
    width: calc((100% - 58px) / 3);
    /* 平均分成3个宽度 */
    height: 32px;
    /* 使用固定高度更容易居中，20% 可能不适合 */
    box-sizing: border-box;
    text-align: center;
    white-space: nowrap;
    font-size: 12px;
}

/* 适合的背景为橙色 */
.suitable {
    background-color: #FFF7E6;
    color: #D46C0A;
}

/* 不适合的背景为灰色 */
.unsuitable {
    background-color: #e3e3e3;
    color: #535251;
}

/* 自定义滚动条样式（Chrome、Safari等基于WebKit的浏览器） */
.env-content::-webkit-scrollbar,
.ai-interviewer-box::-webkit-scrollbar {
    width: 8px;
}

.env-content::-webkit-scrollbar-track,
.ai-interviewer-box::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.env-content::-webkit-scrollbar-thumb,
.ai-interviewer-box::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
}

.env-content::-webkit-scrollbar-thumb:hover,
.ai-interviewer-box::-webkit-scrollbar-thumb:hover {
    background: #555;
    width: 8px;
}

.button-area {
    display: flex;
    justify-content: flex-end;
    padding-right: 15px;
    padding-left: 5px;
}

.next-button {
    margin-top: 3px !important;
    margin-bottom: 3px !important;
    padding: 10px 20px !important;
    font-size: 16px !important;
    background-color: #7d5e01 !important;
    color: #fff !important;
    border: none !important;
    border-radius: 6px !important;
    cursor: pointer !important;
    display: flex;
    /* 启用 flex 布局 */
    align-items: center;
    /* 垂直居中 */
    justify-content: center;
    /* 水平居中 */
    text-align: center;
    /* 多行时文字居中 */
}

.pre-line {
    white-space: pre-wrap;
    line-height: 1.5;
}

.pattern-practice {
    position: relative;
    overflow: hidden;
    width: 50%;
    height: 100%;
    background-color: white;
    color: #666;
    border: #face54 solid 3px;
    border-radius: 20px;
    cursor: pointer;
    font-size: 16px;
    transition: color 0.3s ease;
    display: flex;
    flex-direction: column;
}

.pattern-practice::before {
    content: "";
    position: absolute;
    inset: 0;
    background-image: linear-gradient(to bottom, #face54, #fee9b0);
    opacity: 0;
    transition: opacity 0.3s ease;
    z-index: 0;
}

.pattern-practice:hover::before,
.pattern-practice.active::before {
    opacity: 1;
}

.pattern-practice>* {
    position: relative;
    z-index: 1;
}

.pattern-practice:hover,
.pattern-practice.active {
    color: white;
}

.pattern-real {
    position: relative;
    overflow: hidden;
    width: 50%;
    height: 100%;
    background-color: white;
    color: #666;
    border: #face54 solid 3px;
    border-radius: 20px;
    cursor: pointer;
    font-size: 16px;
    transition: color 0.3s ease;
    display: flex;
    flex-direction: column;
}

.pattern-real::before {
    content: "";
    position: absolute;
    inset: 0;
    background-image: linear-gradient(to bottom, #face54, #fce9b4);
    opacity: 0;
    transition: opacity 0.3s ease;
    z-index: 0;
}

.pattern-real:hover::before,
.pattern-real.active::before {
    opacity: 1;
}

.pattern-real>* {
    position: relative;
    z-index: 1;
}

.pattern-real:hover,
.pattern-real.active {
    color: white;
}

.upload-resume {
    display: block;
}

.scene-title {
    width: 100%;
    height: 20%;
    font-size: 36px;
    font-weight: bold;
    text-align: center;
    padding: 3%;
}

.scene-sub-title {
    font-size: 18px;
    line-height: 1.5;
    padding-bottom: 2%;
    margin: 1% 5% 1% 5%;
}

.practice-bg-img {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 80%;
    height: 60%;
    object-fit: contain;
    z-index: 0;
    /* 确保图片在文字下层 */
    pointer-events: none;
    /* 不影响点击事件 */
}

.mode-bg-img {
    position: absolute;
    right: 0;
    top: 0;
    width: 50%;
    height: 50%;
    object-fit: contain;
    z-index: 0;
    /* 确保图片在文字下层 */
    pointer-events: none;
    /* 不影响点击事件 */
}

.pattern-practice span {
    position: relative;
    z-index: 1;
}

.pattern-real span {
    position: relative;
    z-index: 1;
}
</style>
